# -*- coding: utf-8 -*-
import os
import platform
import sys
from os.path import abspath, sep, split

from program_top.utilities.csv_and_json_serialisation import clean_load_json
from program_top.utilities.my_dir import browse_dir
from program_top.utilities.my_dir import make_ever_dir

platform_notified=False

windows_linesep='\r\n'
try:
	reload(sys)
	sys.setdefaultencoding('utf-8')
	#print('gbk')
except:
	print("这是python3不必设置默认utf-8编码")
	pass

class project_initialisation(object):
	def __init__(self,environment_pack):
		'''项目初始化(未完成，要调试)'''
		project_path=environment_pack['runtime_paths']['program_main_dir']
		config_file=environment_pack['runtime_paths']['config_file_dir']+'utf_file_head.json'
		self.utf_8_line_head=clean_load_json(config_file)['utf_file_head']
		script_list=browse_dir(project_path, '.py')
		
		[self.uniform_each_py_script(each) for each in script_list]
	
	def uniform_each_py_script(self, py_script_name):
		'''
			with open(py_script_name, mode='r+', encoding='utf-8', newline='') as current_file:
				all_file_original_content=current_file.read()
				
				try:
					all_origin_lines=all_file_original_content.splitlines(keepends=True)
					first_line=all_file_original_content[0]
				except:
					
					pass
				
				if not first_line:#如果文件全空
					current_file.write(utf_8_line_head+windows_linesep)
					current_file.close()
					return
				
				whether_start_with_corrent_head=first_line.startswith(utf_8_line_head)#是否用了我喜欢的编码文件头
				whether_endwith_corrent_linesep=first_line.endswith(windows_linesep)#是否使用了windows换行符
				
				if whether_endwith_corrent_linesep and whether_start_with_corrent_head:#如果文件编码头和行末尾都对了，关闭退出不操作
					current_file.close()
					return
				current_file.seek(0, 0)#文件指针重回开头
				
				whether_start_with_encoding_head=first_line.startswith('#')#是否有编码文件头
				
				all_original_contents=current_file.read()
				all_lines=all_original_contents.splitlines()
				
				current_file.truncate()
				
				if not whether_start_with_encoding_head:#如果没有编码文件头
					all_lines[0]=utf_8_line_head+all_lines[0]#原有内容加上文件头
				
				if not whether_start_with_corrent_head:#有编码文件头但是不是我喜欢的格式，替换掉
					all_lines[0]=utf_8_line_head
				
				new_file_content=windows_linesep.join(all_lines)#剩下不满足的文件都是用了linux换行符，统统换成windows的
				new_file_content+=windows_linesep
				
				current_file.write(new_file_content)
				current_file.close()
				pass
			pass
		'''
		pass
	
	pass

def confirm_platform_info():
	'''获取当前平台相关的信息，以字典形式返回出来'''
	
	
	current_platform_name=platform.platform()
	current_system_category='linux' if 'Linux' in current_platform_name else 'windows'#当前系统类别:windows还是linux
	system_encoding_dict={'linux': 'utf-8', 'windows': 'gb18030', 'osx': 'unicode'}
	current_system_encoding=system_encoding_dict[current_system_category]
	
	environment_string="current os: %s, python版本: %s, 操作系统内码: %s"%(
	current_platform_name, platform.python_version(), current_system_encoding)
	
	print(environment_string)
	
	platform_info_dict={'current_system_category': current_system_category,'current_system_encoding': current_system_encoding, 'graphical_backend': 'AGG'}
	return platform_info_dict

def get_current_environment_pack():
	'''返回所有对应的路径变量，生成平台相关的信息'''
	
	from __main__ import __file__ as entry_file
	start_script_absolute_filename=abspath(entry_file)
	runtime_paths={}
	runtime_paths['start_script_absolute_filename']=start_script_absolute_filename
	start_working_directory_stem=split(start_script_absolute_filename)[0]#当前程序的文件夹绝对路径，不包含斜杠
	program_main_dir=start_working_directory_stem+sep
	runtime_paths['program_main_dir']=program_main_dir
	#以下为项目包含文件夹
	
	resource_dir=program_main_dir+'resource_dir'+sep#资源文件根目录，包括图标，图片
	runtime_paths['resource_dir']=resource_dir
	config_file_dir=program_main_dir+'config_dir'+sep#配置文件根目录
	runtime_paths['config_file_dir']=config_file_dir
	extension_dir=program_main_dir+'extensions'+sep#扩展工具根目录
	runtime_paths['extension_dir']=extension_dir
	
	#以下为输入输出文件夹
	input_dir=start_working_directory_stem+',input_dir'+sep#输入数据根目录
	runtime_paths['input_dir']=input_dir
	
	output_dir=start_working_directory_stem+',output_dir'+sep#输出数据根目录
	runtime_paths['output_dir']=output_dir
	
	buffer_dir=start_working_directory_stem+',buffer_dir'+sep#缓存根目录
	runtime_paths['buffer_dir']=buffer_dir
	
	current_platform_info=confirm_platform_info()
	
	environment_pack={'runtime_paths': runtime_paths, 'current_platform_info': current_platform_info}
	#a=project_initialisation(environment_pack)#暂时先不执行项目初始化，因为目前代码文件重复的问题还没有搞清楚
	
	return environment_pack

def environment_initialisation(self, parent=None):
	'''单个类的环境初始化：1.创建环境变量包，然后根据环境变量的路径，创建配置文件文件夹(如果不存在)，读入配置文件。创建日志文件夹，创建日志文件'''
	if hasattr(self, 'parent'):
		self.environment_pack={}
		self.environment_pack.update(self.parent.environment_pack)
	else:
		self.environment_pack=get_current_environment_pack()
	
	instance_dict={
		'config_file_dir': self.environment_pack['runtime_paths']['config_file_dir']+self.__class__.__name__+os.sep,
		'buffer_dir': self.environment_pack['runtime_paths']['buffer_dir']+self.__class__.__name__+os.sep,
		'output_dir': self.environment_pack['runtime_paths']['output_dir']+self.__class__.__name__+os.sep}
	self.environment_pack['instance_path']=instance_dict

	for each_path in instance_dict.values():
		make_ever_dir(each_path)
	pass

def class_environment_initialisation(self):
	'''整个类的环境变量和配置初始化'''
	
	class_object=self.__class__
	class_object.environment_pack=get_current_environment_pack()
	class_dict={
		'config_file_dir': class_object.environment_pack['runtime_paths']['config_file_dir']+class_object.__name__+os.sep,
		'buffer_dir': class_object.environment_pack['runtime_paths']['buffer_dir']+class_object.__name__+os.sep,
		'output_dir': class_object.environment_pack['runtime_paths']['output_dir']+class_object.__name__+os.sep
	}
	class_object.environment_pack['class_path']=class_dict
	
	for each_path in class_dict.values():
		make_ever_dir(each_path)
	pass

